package models

import (
	"time"
	"database/sql"
	"fmt"
)

type SnippCode struct {
	CodeId      int       `json:"cid,omitempty"`
	UserId      int       `json:"uid,omitempty"`
	CodeName    string    `json:"cname,omitempty"`
	CodeAlias   string    `json:"calias,omitempty"`
	CodeContent string    `json:"ccontent,omitempty"`
	TypeId      int       `json:"tid,omitempty"`
	CodeStatus  int       `json:"cstatus,omitempty"`
	CodeTime    time.Time `json:"ctime,omitempty"`
}
type SnippCodes []*SnippCode

func (db *DB) GetCodeListForTag(tageid int) (SnippCodes, error) {
	sts := make(SnippCodes, 0)

	stmt, err := db.Prepare("SELECT c.code_id,c.code_name,c.code_alias,c.code_time FROM snipp_code c INNER JOIN relation_code_tag rct ON c.code_id=rct.code_id WHERE rct.tag_id = ? and c.user_id=0")
	checkErr(err)

	rows, err := stmt.Query(tageid)
	checkErr(err)

	for rows.Next() {
		var codeTime string
		st := new(SnippCode)
		err := rows.Scan(&st.CodeId, &st.CodeName, &st.CodeAlias, &codeTime)
		checkErr(err)
		st.CodeTime, _ = time.Parse("2006-01-02 15:04:05", codeTime)

		sts = append(sts, st)
	}
	checkErr(err)
	return sts, nil

}

//通过代码ID获取代码详细内容
func (db *DB) GetCodeForId(code_id int) (*SnippCode, error) {
	codelist := new(SnippCode)
	var codeTime string

	stmt, err := db.Prepare("SELECT code_id, user_id, code_name, code_alias, code_content, type_id, code_status, code_time FROM snipp_code WHERE code_id=? AND user_id=0")
	checkErr(err)

	rows := stmt.QueryRow(code_id)

	err = rows.Scan(&codelist.CodeId, &codelist.UserId, &codelist.CodeName, &codelist.CodeAlias, &codelist.CodeContent, &codelist.TypeId, &codelist.CodeStatus, &codeTime)
	codelist.CodeTime, _ = time.Parse("2006-01-02 15:04:05", codeTime)

	if err == sql.ErrNoRows {
		fmt.Print("没有结果")
	} else {
		checkErr(err)
	}
	return codelist, nil
}

//获取全部代码列表
func (db *DB) GetCodeListAll() (SnippCodes, error) {
	sts := make(SnippCodes, 0)

	stmt, err := db.Prepare("SELECT c.code_id,c.code_name,c.code_alias,c.code_time FROM snipp_code c WHERE c.user_id=0")
	checkErr(err)

	rows, err := stmt.Query()
	checkErr(err)

	for rows.Next() {
		var codeTime string
		st := new(SnippCode)
		err := rows.Scan(&st.CodeId, &st.CodeName, &st.CodeAlias, &codeTime)
		checkErr(err)
		st.CodeTime, _ = time.Parse("2006-01-02 15:04:05", codeTime)

		sts = append(sts, st)
	}
	checkErr(err)
	return sts, nil
}

//插入代码
func (db *DB) InsertCode(code *SnippCode) int64 {
	stmt, err := db.Prepare("INSERT INTO `snippets_box`.`snipp_code`(`user_id`, `code_name`, `code_alias`, `code_content`, `type_id`, `code_status`, `code_time`) VALUES (?,?,?,?,?,?,?)")
	checkErr(err)

	res, err := stmt.Exec(code.UserId, code.CodeName, code.CodeAlias, code.CodeContent, code.TypeId, code.CodeStatus, code.CodeTime)
	checkErr(err)

	id, err := res.LastInsertId()
	checkErr(err)

	return id

}
